<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>路线规划</title>
    <link rel="stylesheet" href="res/layui.css" media="all">
    <style type="text/css">
        .map-left {
            height:100vh;overflow: auto; padding: 10px;
        }
        .page {
            width: 100%; background-color: #eee;
        }
        .address-content .label {
            width: 30%;
            display: inline-block;
        }
        .address-content .text {
            width: 70%;
            display: inline-block;
        }
    </style>
    <!--Map-->
    <style type="text/css">
        #container {
            height:100vh;
        }
    </style>
</head>
<body>

<div class="page">
    <div class="layui-row content">
        <div class="layui-col-md3 map-left">
            <div class="layui-card">
                <div class="layui-card-header">筛选订单</div>
                <div class="layui-card-body">
                        <div class="layui-form-item">
                            <label class="layui-form-label">开始时间</label>
                            <div class="layui-input-block">
                                <input class="layui-input" placeholder="起始时间"
                                       @keyup.enter="search()"
                                       v-model="time1" autocomplete="off" id="startDate">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">结束时间</label>
                            <div class="layui-input-block">
                                <input class="layui-input" placeholder="结束时间"
                                       @keyup.enter="search()"
                                       v-model="time2" autocomplete="off" id="endDate">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">订单状态</label>
                            <form class="layui-form">
                            <div class="layui-input-block">
                                <select v-model="status" id="status">
                                    <option value="11">待发货</option>
                                    <option value="0">全部</option>
                                    <option value="10">待付款</option>
                                    <option value="20">已发货</option>
                                </select>
                            </div>
                            </form>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label"></label>
                            <button type="button" class="layui-btn layui-btn-sm" @click="search">搜索</button>
                        </div>

                    <div>共计{{count}}个订单</div>
                    <div>已规划
                        <span style="color: #2509dc;font-weight: bolder;margin: 0 5px">{{plans}}</span>个订单，未规划订单
                        <span style="color: red;font-weight: bolder;margin: 0 5px; cursor: pointer" @click="showunmark">{{count - plans - express}}</span>个
                        ，物流单<span style="color: #dc5f03;font-weight: bolder;margin: 0 5px">{{express||0}}</span>个
                    </div>
                    <div v-if="unmarks>0">
                        <a target="_blank" href="#" @click="download">还有<span style="color: red;font-weight: bolder;margin: 0 5px">{{unmarks}}</span>
                            个订单地址未被标记</a>
                    </div>
                </div>
            </div>

            <div class="layui-card" v-for="(item, index) in routeList" :key="index">
                <div class="layui-card-header">选择路线
                    <button type="button" class="layui-btn layui-btn-sm"
                            :style="{'background-color': '#' + item.routecolor, 'margin-left': '20px'}">
                        {{item.routename}}
                    </button>
                </div>
                <div class="layui-card-body address-content">
                    <span class="text" style="width: 100%">
                          <button type="button"
                                  :class="curRouteIndex == index ? 'layui-btn-disabled': ''"
                                  class="layui-btn layui-btn-sm" @click="startPlan(index)">开始设置</button>
                          <button type="button" class="layui-btn layui-btn-sm" @click="savePlan(index)">保存路线</button>
                          <button type="button" class="layui-btn layui-btn-sm" @click="clearPlan(index)">清除路线</button>
                    </span>
                </div>
            </div>
            <div class="layui-card">
                <div class="layui-card-header">选择路线
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary"
                            :style="{'margin-left': '20px'}">
                        物流单
                    </button>
                </div>
                <div class="layui-card-body address-content">
                    <span class="text" style="width: 100%">
                          <button type="button" class="layui-btn layui-btn-sm" @click="saveExpress()">保存路线</button>
                    </span>
                </div>
            </div>
        </div>
        <div class="layui-col-md9 map-right">
            <div id="container"></div>
        </div>
    </div>
</div>
<!--初始加载时，需查询条件完全一致才返回上次标记数据，原因是时间不一致返回的同一个标记点中有的订单已标记，而有的未标记情况-->
<script src="res/layui.js"></script>
<script src="res/vue.js"></script>
<script src="./res/axios.min.js"></script>
<script src="res/jquery.js"></script>
<script src="res/layer/layer.js"></script>

<script type="text/javascript">
    Vue.prototype.$axios = axios;   // 2、在vue中使用axios
    var app = new Vue({
        el: '.map-left',
        data: {
            addressList:[],
            markerList:[],
            routeList: [],//路线列表
            routeItemList: [],//[[0]=>[item1,item2],...]
            count: 0,//总的订单数
            plans: 0,//已规划数
            express:0,//物流单数
            unmarks:0,//未被标记订单数

            //form 表单查询
            time1: '',
            time2: '',
            status: '11',

            //业务值
            curRouteIndex: -1,
            defaultColor: '#888',
            routeColors: {},
            zindex: 13,
        },
        mounted() {
            this.initQuery()
        },
        /*
        * 初始化marker时：
        *   1.根据返回订单列表创建marker，并绑定data至marker中
        *   2.判断每个marker是否有归属路线，有则添加至对应点routeItems中，并设置标签颜色
        * 开始标记时：
        *   1.设置curRouteIndex为点击按钮路线序号
        * 取消标记时：
        *   1.调用接口保存删除信息
        *   2.根据marker中的序号移除对应路线下订单列表中该项数据，
        *   3.重新加载地图中对应路线下所有marker
        *   4.删除marker中的routeid、颜色及所在当前路线中的序号（routeItems的长度），
        * 点击标记时：
        *   1.根据当前routeid，设置marker中的routeid、颜色及所在当前路线中的序号（routeItems的长度），
        *   2.变更当前marker颜色及标签序号
        *   3.将当前marker添加至路线子项列表routeItems中，
        * 保存路线时：序列化当前按钮所在路线下全部订单数据，调用接口保存
        * 清除路线时：
        *   1.根据按钮所在路线，遍历列表项删除marker中的routeid、颜色及所在当前路线中的序号，
        *   2.遍历列表清除marker颜色及标签序号
        *   3.清空路线对应订单子项routeItems
        * */
        methods: {
            post(url, param) {
                return this.$axios.post(url, this.convertObj(param), {headers:{'Content-Type':'application/x-www-form-urlencoded'}})
            },
            convertObj(data) {
                var _result = [];
                for (var key in data) {
                    var value = data[key];
                    if(value) {
                        if (value.constructor == Array) {
                            value.forEach(function(_value) {
                                _result.push(key + "=" + _value);
                            });
                        } else {
                            _result.push(key + '=' + value);
                        }
                    }
                }
                return _result.join('&');
            },
            loadData() {
                let that = this;
                this.post('/education/admin/route/list', {}).then(function (rs) {
                    var res = rs.data;
                    if(res.status == 200) {
                        that.routeList = res.data
                        let map = {}
                        for(let i=0; i<that.routeList.length; i++) {
                            that.routeItemList[i] = []
                            map[that.routeList[i].id] = that.routeList[i].routecolor
                        }
                        that.routeColors = map
                        //that.routeItemList = res.data.routeItemList
                    }
                })
            },
            initQuery() {
                let d = new Date()
                let o = this.formatDate(d);
                this.time2 = o.y + '-' + o.m + '-' + o.d + ' 00:00:00'
                d.setDate(d.getDate() - 1)
                o = this.formatDate(d);
                this.time1 = o.y + '-' + o.m + '-' + o.d + ' 00:00:00'
            },
            formatDate(date) {
                var o = {
                    y: date.getFullYear(),
                    m: date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1, //月份
                    d: date.getDate() < 10 ? '0' + date.getDate() : date.getDate(), //日
                    h: date.getHours() < 10 ? '0' + date.getHours() : date.getHours(), //小时
                    f: date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(), //分
                    s: date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(), //秒
                };
                return o;
            },
            startPlan(index) {
                if(this.curRouteIndex != -1) {
                    layer.msg('请先保存原路线')
                    return
                }
                this.curRouteIndex = index
            },
            addMarkerToRoute(marker, color) {
                //1.设置marker的data
                let list = this.routeItemList[this.curRouteIndex]
                //let idx = list.length >0 ? list[list.length-1].getExtData().idx + 1 : 1
                let idx = list.length + 1;
                let data = marker.getExtData();
                data.routeid = this.routeList[this.curRouteIndex].id
                data.idx = idx
                marker.setExtData(data)
                //2.变更颜色
                let s = marker.getContent().replace(/fill=.*?>/, 'fill="'+color+'">')
                s = s.replace(/white.*?</, 'white">'+idx+'<')
                marker.setContent(s)
                //3.添加至数组项
                list.push(marker)
                console.log('routemarklist: ', list)
            },
            /*
            取消标记，本地删除，然后保存路线数据
             */
            delMarker(marker) {
                let data = marker.getExtData();
                let routeid = data.routeid
                if(!routeid) return
                layer.confirm('是否确定取消标记?', {icon: 3, title:'提示'}, (index) => {
                    let ci = this.getRouteIndexById(routeid)
                    this._delMarker(marker, routeid)
                    this.savePlan(ci)

                    layer.close(index);
                });
            },
            _delMarker(marker, routeid) {
                //2.移除routeItems列表项中的数据
                let i = this.getRouteIndexById(routeid)
                let items = this.routeItemList[i]
                let del = 0
                for(let k=0; k<items.length; k++) {
                    if(items[k].getExtData().idx == marker.getExtData().idx) {
                        del = k;
                        break
                    }
                }
                items.splice(del, 1)
                //3.重新加载routeItemsList中marker显示
                this.refreshMarkerInfo(items)
                //4.清除信息
                this.clearMarkerInfo(marker)
            },
            log(list) {let tt = []
                for(var i=0; i<list.length; i++) {
                    tt.push(list[i].getExtData().idx)
                }
                console.log(tt)
            },
            refreshMarkerInfo(routeItems) {
                for(let i=0; i<routeItems.length; i++) {
                    let marker = routeItems[i]
                    let data = marker.getExtData();
                    let idx = i+1;
                    data.idx = idx
                    marker.setExtData(data)
                    let s = marker.getContent()
                    s = s.replace(/white.*?</, 'white">'+idx+'<')
                    marker.setContent(s)
                }
            },
            saveExpress() {
                this.post('/education/admin/pages/routePlan/saveExpress', this.getRequestParam()).then(function (rs) {
                    var res = rs.data;
                    if(res.code == 200) {
                        layer.msg('保存成功');
                    } else {
                        layer.msg('保存失败')
                    }
                })
            },
            savePlan(index) {
                let items = this.routeItemList[index]
                //items 为marker的列表，需要转换为对应的id
                let routeid = this.routeList[index].id
                let name = this.routeList[index].routename ||''

                let arr = []
                for(let i=0; i<items.length; i++) {
                    let o = items[i].getExtData()
                    o.address =''
                    //arr.push(o)
                    arr[o.idx-1] = o
                }
                let time1 = this.time1, time2 = this.time2, status = this.status;
                let param = {itemJson: JSON.stringify(arr), routeid, time1, time2, status}
                this.post('/education/admin/pages/routePlan/save', param).then((rs) => {
                    var res = rs.data;
                    if(res.code == 200) {
                        layer.msg(name +'保存成功');
                        //this.curRouteIndex = -1
                    } else {console.log(rs)
                        layer.msg('保存失败')
                    }
                })
            },
            clearPlan(index) {
                let items = this.routeItemList[index]
                //1.清除list的marker颜色,label
                for(let i=0; i<items.length; i++) {
                    this.clearMarkerInfo(items[i])
                }
                //2.清空子项itemRoutes
                this.routeItemList[index] = []
            },
            clearMarkerInfo(marker) {
                let s = marker.getContent().replace(/fill=.*?>/, 'fill="'+this.defaultColor+'">')
                s = s.replace(/white.*?</, 'white">'+''+'<')
                marker.setContent(s)
                let data = marker.getExtData()
                data.routeid = '';
                data.idx = '';
                marker.setExtData(data)
            },
            download() {
                let url = '/education/admin/export?type=unmark&' + this.convertObj(this.getRequestParam());
                window.open(url)
            },
            getRequestParam() {
                let param = {time1: document.getElementById('startDate').value,
                    time2: document.getElementById('endDate').value, status: document.getElementById('status').value}
                if(!(param.time1 && param.time2)) {
                    layer.msg('请选择查询条件')
                    throw SyntaxError();
                }
                return param;
            },
            search() {
                let that = this;
                this.post('/education/admin/pages/routePlan/getOrderList', this.getRequestParam()).then(function (rs) {
                    let res = rs.data;
                    if(res.status == 200) {
                        if(res.data !=null) {
                            console.log(res.data)
                            that.addressList = res.data.list;
                            that.count = res.data.count
                            that.express = res.data.express
                            that.plans = res.data.plans;
                            that.unmarks = res.data.unmarks;
                            for(let i=0; i<that.routeList.length; i++) {
                                that.routeItemList[i] = []
                            }
                            that.showMarkInMap(that.addressList)
                            that.initPlanData()

                            if(that.unmarks) {
                                layer.msg('还有' + that.unmarks + '个地址未被标记');
                            }
                        }
                    } else if(res.status == 401){
                        layer.msg('请先登录')
                    }
                })
            },
            /*排序，然后重新设置标签*/
            initPlanData() {
                let list = this.markerList;

                for(let i=0; i<list.length; i++) {
                    let data = list[i].getExtData()
                    let routeid = data.routeid;
                    if(routeid) {
                        this.initRouteItem(list[i], routeid)
                    }
                }
                //子路由标记列表mark排序，!!!
                for(let i=0; i<this.routeItemList.length; i++) {
                    let rlist = this.routeItemList[i]
                    rlist.sort(function (a, b) {
                        return (Number(a.getExtData().idx || 0) - Number(b.getExtData().idx || 0))
                    })
                }
            },
            getRouteIndexById(routeid) {
                let routeList = this.routeList
                for(let i=0; i< routeList.length; i++) {
                    if(routeList[i].id == routeid) {
                        return i
                    }
                }
                return -1
            },
            initRouteItem(marker, routeid) {
                let index = this.getRouteIndexById(routeid)
                if(index == -1) return
                let color= this.routeList[index].routecolor;

                //2.变更颜色
                let idx = marker.getExtData().idx;
                let s = marker.getContent().replace(/fill=.*?>/, 'fill="#'+color+'">')
                s = s.replace(/white.*?</, 'white">'+idx+'<')
                marker.setContent(s)

                //3.添加至数组项
                this.routeItemList[index].push(marker)
            },
            showMarkInMap(list) {
                let markerList = []
                for(var i=0; i<list.length; i++) {
                   let o = list[i];
                   if(o.stationid && o.station_marklat) {//自提
                       let a = common_map.createMarker2('', [o.station_marklng, o.station_marklat], i, this.defaultColor)
                       let num = o['idarr'] && o['idarr'].length
                       if(num > 1) {
                           a.setLabel({content: '自提' + num + '单'})
                       }
                       a.setTitle('自提点：' + o.station_name)
                       a.setExtData(o)
                       markerList.push(a)
                   } else { //普通地址
                       if(o.is_mark==1 && o.marklng) {
                           let a = common_map.createMarker2('', [o.marklng, o.marklat], i, this.defaultColor)
                           a.setExtData(o)
                           a.setTitle(o.address||'')
                           markerList.push(a)
                           let num = o['idarr'] && o['idarr'].length
                           if(num > 1) {
                               a.setLabel({ content: num + '单' })
                           }
                       }
                   }
                }
                this.initMap(markerList)
                common_map.clearMap()
                common_map.addMarkers(markerList)
                common_map.setCenter()
                this.markerList = markerList
            },
            initMap(arr) {
                //注册右键事件
                var contextMenu = new AMap.ContextMenu();
                contextMenu.addItem("取消设置",  (e)=> {
                    this.delMarker(this.currentMarker)
                }, 0);
                for(let i=0; i< arr.length; i++) {
                    let marker = arr[i]
                    marker.on('rightclick', (e)=> {
                        this.currentMarker = marker
                        contextMenu.open(map, e.lnglat);
                    })
                    marker.on('click', (e)=> {
                        this._click(marker);
                    })
                }
            },
            _click(marker) {
                if(this.curRouteIndex == -1) return
                let data = marker.getExtData()
                if(data.routeid) {
                    layer.msg('已被标记，请先取消设置')
                    return
                }
                console.log('click marker :', data)
                this.addMarkerToRoute(marker, '#' + this.routeList[this.curRouteIndex]['routecolor'])
            },
            showunmark() {
                let list = this.markerList
                for(let i=0; i<list.length; i++) {
                    let o = list[i]
                    let s = /fill="#888/
                    if(s.test(o.getContent())) {
                        o.setzIndex(this.zindex++)
                    }
                }
            }
        }
    })
    window.onload = function () {
        app.loadData()
    }
</script>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=effff8de239e3c06c98cd3c45694afcc"></script>
<script type="text/javascript" src="map.js"></script>
<script type="text/javascript">
    layui.use(['laydate','form'], function(){
        var laydate = layui.laydate;

        //执行一个laydate实例
        laydate.render({
            elem: '#startDate' //指定元素
            ,type: 'datetime'
            ,done: function(value, date, endDate){
//                console.log(value); //得到日期生成的值，如：2017-08-18
//                console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
//                console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
                app.time1 = value
            }
        });
        laydate.render({
            elem: '#endDate' //指定元素
            ,type: 'datetime'
            ,done: function(value, date, endDate){
                app.time2 = value
            }
        });
        var form = layui.form;
        form.on('select', function(data){
            console.log('select:', data.value); //得到被选中的值
            app.status = data.value
        });
    });

</script>
</body>